package zmee.pmct.formplugin.pmas;

import kd.bos.ai.util.JsonUtil;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.DispatchServiceHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kd.bos.util.HttpClientUtils;
import zmee.util.GetCwgxAccessTokenUtil;
import zmee.util.DBUtil;

public class BeforeUnexamPurContractPlugin extends AbstractOperationServicePlugIn {

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {

        DynamicObject[] dataEntities = e.getDataEntities();
        DynamicObject pur_contract = dataEntities[0];
        DynamicObject outcontract = BusinessDataServiceHelper.loadSingle(pur_contract.get(0), "pmct_outcontract");
        String combofield = outcontract.getString("zmee_combofield");
        if (pur_contract != null && "02".equals(combofield)) {
            String billno = pur_contract.get("billno").toString();
            //List<Object> inputs = new ArrayList<>(1);
            HashMap<String,Object> inputs = new HashMap<>();
            inputs.put("billno",billno);
            String accesstoken = GetCwgxAccessTokenUtil.getAccesstoken("18205188770");
            String cqUrl = DBUtil.getParamValue("CQUrl");
            String url = "/kapi/app/iscb/sf_purcontractunexam";
            url=cqUrl+url;
            HashMap<String, String> header = new HashMap<>();
            header.put("accesstoken",accesstoken);
            String result = null;
            try {
                result = HttpClientUtils.postAppJson(url, header, inputs);
            } catch (IOException exception) {
                exception.printStackTrace();
            }

            //Map result = DispatchServiceHelper.invokeBizService("isc", "iscb",
                    //"IscFlowService", "execute", "purcontractunexam", inputs);

            Map returndata = (Map) JsonUtil.decodeFromString(result,HashMap.class);
            Map data = (Map) returndata.get("data");
            Map output = (Map) data.get("output");
            //isunexam: 0 : 未查询到数据 , 1 : 不能反审核,2 : 执行成功
            Integer isunexam = (Integer) output.get("isunexam");
            if (isunexam == 0){
                e.setCancelMessage("检测到EAS不存在合同，已反审核成功");
            }else if (isunexam ==1){
                e.setCancel(true);
                e.setCancelMessage("查询到eas采购合同反审核失败，详细信息请到eas查看");
            }
        }

        super.beforeExecuteOperationTransaction(e);
    }
}
